package com.gzdh.tang.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 单数据源配置（jeecg.datasource.open = false时生效）
 *
 * @Author zhoujf
 */
@Configuration
@MapperScan(value = {"com.gzdh.tang.**.mapper*"})
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        // 设置sql的limit为无限制，默认是500
        return new PaginationInterceptor().setLimit(-1);
    }

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    public static ThreadLocal<String> myTableName = new ThreadLocal<>();

    //    @Bean
//    public MybatisPlusInterceptor mybatisPlusInterceptor() {
//        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
//        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
//            put("t_messages", (sql, tableName) -> {
//                return myTableName.get();
//            });
//        }};
//        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
//        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
//        return interceptor;
//    }
    @Bean
    public PaginationInterceptor paginationInterceptor2() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
        dynamicTableNameParser.setTableNameHandlerMap(getTableNameHandlerMap());
        paginationInterceptor.setSqlParserList(Collections.singletonList(dynamicTableNameParser));
        return paginationInterceptor;
    }

    private Map<String, ITableNameHandler> getTableNameHandlerMap() {
        Map<String, ITableNameHandler> tableNameHandlerMap = new HashMap<>();
        //编码灶类动态表名
        tableNameHandlerMap.put("bmzl", (metaObject, sql, tableName) -> {
                    Object param = getParamValue("tableNameAddress", metaObject);
                    String params = param != null ? String.valueOf(param) : "";
                    return tableName + params;
                }
        );
        //WeekmenuBak动态表名
        tableNameHandlerMap.put("ZWEEKMENUBAK", (metaObject, sql, tableName) -> {
                    Object param = getParamValue("tableNameAddress", metaObject);
                    String params = param != null ? String.valueOf(param) : "";
                    return tableName + params;
                }
        );
        return tableNameHandlerMap;
    }

    /**
     * 获取参数值
     */
    private Object getParamValue(String title, MetaObject metaObject) {
        //获取参数
        Object originalObject = metaObject.getOriginalObject();
        JSONObject originalObjectJSON = JSON.parseObject(JSON.toJSONString(originalObject));
        JSONObject boundSql = originalObjectJSON.getJSONObject("boundSql");
        try {
            JSONObject parameterObject = boundSql.getJSONObject("parameterObject");
            return parameterObject.get(title);
        } catch (Exception e) {
            return null;
        }
    }

}
